package group.itk.vuelogintestbackend.login

import com.google.gson.JsonObject
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.AuthenticationException
import org.apache.shiro.authc.IncorrectCredentialsException
import org.apache.shiro.authc.UnknownAccountException
import org.apache.shiro.authc.UsernamePasswordToken
import org.springframework.stereotype.Service

@Service
class LoginServiceImpl : LoginService {
    override fun login(token: UsernamePasswordToken): JsonObject {
        val jsonObject = JsonObject()

        try {
            val currentUser = SecurityUtils.getSubject()
            currentUser.login(token)
            return jsonObject.apply {
                addProperty("msg","login ok")
                addProperty("code",200)
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
            jsonObject.addProperty("msg", "login failed")
            jsonObject.addProperty("code",400)
            when (ex) {
                is UnknownAccountException  -> {
                    jsonObject.addProperty("exception", "用户名不存在或密码错误")
                    return jsonObject
                }
                is IncorrectCredentialsException -> {
                    jsonObject.addProperty("exception", "用户名不存在或密码错误")
                    return jsonObject
                }
                is AuthenticationException -> {
                    jsonObject.addProperty("exception", ex.toString())
                    return jsonObject
                }
            }
        }
        jsonObject.addProperty("code",401)
        jsonObject.addProperty("msg", "login failed")
        jsonObject.addProperty("exception", "发生了未知错误")
        return jsonObject
    }

    override fun logout(): JsonObject {
        SecurityUtils.getSubject().logout()
        return JsonObject().apply {
            addProperty("code",200)
            addProperty("msg","logout ok")
        }
    }
}
